package com.jyw.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jyw.system.domain.SysOrderFaultConfig;
import com.jyw.system.domain.dto.SysOrderFaultConfigEditDto;
import com.jyw.system.domain.vo.SysOrderFaultConfigVo;
import com.jyw.system.mapper.SysOrderFaultConfigMapper;
import com.jyw.system.service.ISysOrderFaultConfigService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Created by ZhangCheng on 2023/08/18
 */
@Service
public class SysOrderFaultConfigServiceImpl extends ServiceImpl<SysOrderFaultConfigMapper, SysOrderFaultConfig> implements ISysOrderFaultConfigService {

    @Override
    public List<Tree<Long>> queryTreeList() {
        List<SysOrderFaultConfigVo>  allList=this.baseMapper.queryConfigList();
        return convertTree(allList);
    }

    private List<Tree<Long>>  convertTree(List<SysOrderFaultConfigVo>  allList){
        List<TreeNode<Long>> treeNodes=allList.stream()
                .map(config -> {
                    TreeNode<Long> node = new TreeNode<>();
                    //下面四个属性是树型结构必有的属性
                    node.setId(config.getId());
                    node.setName(config.getName());
                    node.setParentId(config.getParentId());
                    node.setWeight(config.getSort());
                    // 以下为扩展属性（业务不一样属性也不一样）
                    Map<String, Object> extra = new HashMap<>();
                    extra.put("minTime", config.getMinTime());
                    extra.put("maxTime", config.getMaxTime());
                    extra.put("unit", config.getUnit());
                    extra.put("configId", config.getConfigId());
                    extra.put("value", config.getValue());
                    node.setExtra(extra);
                    return node;
                }).collect(Collectors.toList());

        //作用：将集合数据转为树型结构数据
        //参数一：泛型为TreeNode的list集合，参数二：需要数据的根节点父id
        List<Tree<Long>> result= TreeUtil.build(treeNodes,null);
        return result;
    }

    @Override
    public List<SysOrderFaultConfigVo> queryAllList() {
        return this.baseMapper.queryConfigList();
    }

    @Override
    public void updateTime(SysOrderFaultConfigEditDto editDto) {
        if(editDto.getConfigId()!=null){
            SysOrderFaultConfig config=BeanUtil.copyProperties(editDto,SysOrderFaultConfig.class);
            config.setId(editDto.getConfigId());
            this.baseMapper.updateTime(config);
        }else{
            SysOrderFaultConfig config=BeanUtil.copyProperties(editDto,SysOrderFaultConfig.class);
            this.save(config);
        }
    }
}
